package com.alibaba.citrus.ots.platform.enhance.facade.sls;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.epoch.app.crplatformenhance.domain.operatelog.model.OperateLog;
import com.github.difflib.text.DiffRow;
import com.github.difflib.text.DiffRowGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: qiaojiange
 * @create: 2021/11/10
 * @Description JSON 对比处理器
 */
@Component
public class JsonDiffProcessor implements DiffProcessor {

    @Override
    public void diff(OperateLog operateLog) {
        //如果都是空的，就不用对比
        if (Objects.isNull(operateLog.getOldValue())
                && Objects.isNull(operateLog.getNewValue())) {
            return;
        }

        List<String> oldValueRowList = obtainLineList(operateLog.getOldValue());
        List<String> newValueRowList = obtainLineList(operateLog.getNewValue());
        List<DiffRow> diffRows = DiffRowGenerator.create().showInlineDiffs(false).build()
                .generateDiffRows(oldValueRowList, newValueRowList);

        List<DiffRow> list = new ArrayList<>();
        diffRows.forEach(e -> {
            if (!e.getTag().equals(DiffRow.Tag.EQUAL)) {
                list.add(e);
            }
        });

        if (CollectionUtils.isNotEmpty(list)) {
            operateLog.setDiff(JSON.toJSONString(list));
        }
    }

    /**
     * 将数据打平成美化后的 JSON
     *
     * @param value
     * @return
     */
    private List<String> obtainLineList(String value) {
        List<String> result = new ArrayList<>();
        if (value == null) {
            return result;
        }
        if (value.contains("{") && value.contains("}")) {
            String formatValue = JSON.parseObject(value).toString(
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.MapSortField,
                    SerializerFeature.UseISO8601DateFormat);
            result = splitToLineList(formatValue);
        } else {
            result.add(value);
        }
        return result;
    }


    /**
     * 将每行的字符串保存成列表
     *
     * @param value
     * @return
     */
    private List<String> splitToLineList(String value) {
        List<String> list = new ArrayList<>();
        if (value == null) {
            return list;
        }
        String[] array = value.split("\n\t");
        for (int i = 0; i < array.length - 1; i++) {
            list.add(array[i]);
        }

        //处理最后一个'\n'
        String[] split = array[array.length - 1].split("\n");
        if (split.length > 1) {
            String str = "";
            for (int i = 0; i < split.length - 1; i++) {
                str += split[i];
            }
            list.add(str);
            list.add(split[split.length - 1]);
        }
        return list;
    }
}
